goog.provide('td');

goog.require('Stefan.Timer');
goog.require('td.Map');
goog.require('td.Controller');
goog.require('td.Levels');

//千万不要重写td对象

td.STAGE_WIDTH = 800;
td.STAGE_HEIGHT = 600;
td.GRIDSIZE = 50;
//出怪间隔
td.ARMY_INTERVAL = 15000;


td.GAME = (function() {
	return {
		life: 30,
		money: 5,
		paused: false,
		start: function() {
			T.dom.setStyle('loading', 'display', 'none');
			this.time = 0;
			this.map = new td.Map({
				columns: 10,
				rows: 10,
				gridSize: 50,
				type: 'main'
			});
			this.controller = new td.Controller({
				columns: 3,
				rows: 2,
				gridSize: 50,
				type: 'control'
			});
			this.schedule();
			this.resume();
			
			var __this = this;
			T.on(document, 'contextmenu', function(event) {
				T.event.stop(event);
				var map = __this.getSelectMap();
				if(map.selectedWeapon){
					td.Weapon.getMask(map.selectedWeapon).hide(true);
					var grid = map.grids[map.selectedWeapon - 1]
					grid.setFill(grid.color);
					map.selectedWeapon = null;
				}
				if(__this.map.selectWeapon) {
		    		var grid = __this.map.selectWeapon.grid;
		    		grid.setFill(grid.defaultColor);
		    		__this.map.selectWeapon = null;
		    	}
			});
			T.on(document, 'mousemove', function(event) {
				var p = T.dom.getPosition(__this.map.canvas);
				var w = __this.map.canvas.clientWidth;
				var h = __this.map.canvas.clientHeight;
				var type = __this.getSelectMap().selectedWeapon;
				if(type && (p.left > event.pageX || p.left + w < event.pageX ||
					p.top > event.pageY|| p.top + h < event.pageY)) {
						td.Weapon.getMask(type).hide(true);
					}
					
			});
			if(td.Levels.length) __this.map.grids[0].addArmy(td.Levels.shift());
		},
		getSelectMap: function() {
			return this.controller.selectMap;
		},
		schedule: function() {
		    Stefan.Timer.register(this.step);
		},
		resume: function() {
			Stefan.Timer.active();
			if(!this.time) this.time = new Date().valueOf();
			else {
				this.time = new Date().valueOf() - this.stopTimeInterval;
			}
		},
		stop: function() {
			Stefan.Timer.disable();
			this.stopTimeInterval = new Date().valueOf() - td.GAME.time;
		},
		step: function() {
			if(new Date().valueOf() - td.GAME.time > td.ARMY_INTERVAL) {
				if(td.Levels.length) td.GAME.map.grids[0].addArmy(td.Levels.shift());
				td.GAME.time = new Date().valueOf();
			}
	    	var armyArr = td.GAME.map.armyArr;
	    	for(var i = 0, maxi = armyArr.length; i < maxi; i++){
	    		if(armyArr[i])
	    			armyArr[i].step();
	    	}
	    	var bulletArr = td.GAME.map.bulletArr;
	    	for(var i = 0, maxi = bulletArr.length; i < maxi; i++){
	    		if(bulletArr[i])
	    			bulletArr[i].step();
	    	}
	    	var gridArr = td.GAME.map.grids;
	    	for(var i = 0, maxi = gridArr.length; i < maxi; i++){
	    		if(gridArr[i] && gridArr[i].building !== null)
	    			gridArr[i].building.step();
	    	}
		}
	}
})();


